package com.zbl.advice;

import com.zbl.enumerate.ResultTypeEnum;
import com.zbl.exception.BusinessException;
import com.zbl.result.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 对响应的异常信息进行包装，没出现一种业务异常都需要报装
 *
 * @author wyj
 * @date 2022/8/18 19:40
 */
@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new R(ResultTypeEnum.PARAM_VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public R APIExceptionHandler(BusinessException e) {
        // TODO WYJ log.error(e.getMessage(), e); 由于还没集成日志框架，暂且放着
        return new R(e.getCode(), e.getMsg(), e.getMessage());
    }
}